package com.loong.ems.service.impl;

import com.loong.ems.domain.entity.EmpAttendanceRecord;
import com.loong.ems.domain.vo.resp.EmpAttendanceRecordVo;
import com.loong.ems.domain.vo.resp.NameValueResult;
import com.loong.ems.mapper.EmpAttendanceRecordMapper;
import com.loong.ems.mapper.EmployeeMapper;
import com.loong.ems.mapper.SysUserMapper;
import com.loong.ems.service.EmpAttendanceRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author 龙勇-229970722
 * @date 2025-01-03 10:07
 * @description: 打卡考勤实现类
 */

@Service
public class EmpAttendanceRecordServiceImpl implements EmpAttendanceRecordService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private EmpAttendanceRecordMapper empAttendanceRecordMapper;
    /**
     * 根据id获取打卡记录
     * @param id
     * @return
     */
    @Override
    public List<EmpAttendanceRecord> getCard(Long id) {
        return empAttendanceRecordMapper.getCard(id);
    }

    /**
     * 打卡签到/签退
     * @param id
     * @return
     */
    @Override
    public String clockIn(Long id) {
        // 验证用户有效性
        if (id == null) {
            return "用户ID不能为空";
        }

        // 获取当前日期和时间，设置为北京时间
        LocalDateTime currentDateTime = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
        LocalTime currentTime = currentDateTime.toLocalTime();

        // 设置签退的截止时间为 17:00
        LocalTime cutoffTime = LocalTime.of(17, 0);

        // 创建考勤记录
        EmpAttendanceRecord attendanceRecord = new EmpAttendanceRecord();
        attendanceRecord.setUserId(id);

        // 将当前日期设置为考勤日期，设置为北京时间
        LocalDate localDate = LocalDate.now(ZoneId.of("Asia/Shanghai"));
        Date attendanceDate = Date.from(localDate.atStartOfDay(ZoneId.of("Asia/Shanghai")).toInstant());
        attendanceRecord.setAttendanceDate(attendanceDate); // 设置考勤日期为当前日期

        // 判断当前时间是否在 17:00 之后
        if (currentTime.isAfter(cutoffTime)) {
            // 进行签退操作
            Date checkOutTime = Date.from(currentDateTime.atZone(ZoneId.of("Asia/Shanghai")).toInstant());
            attendanceRecord.setCheckOutTime(checkOutTime); // 设置签退时间为当前时间

            // 检查当天是否已签退
            EmpAttendanceRecord existingRecord = empAttendanceRecordMapper.getAttendanceByDate(id, attendanceRecord.getAttendanceDate());
            if (existingRecord != null && existingRecord.getCheckOutTime() == null) {
                existingRecord.setCheckOutTime(checkOutTime);
                empAttendanceRecordMapper.update(existingRecord); // 更新已有考勤记录
                return "打卡成功";
            } else {
                return "今天尚未签到，无法签退";
            }
        } else {
            // 进行签到操作
            Date signInTime = Date.from(currentDateTime.atZone(ZoneId.of("Asia/Shanghai")).toInstant());
            attendanceRecord.setSignInTime(signInTime); // 设置签到时间为当前时间

            // 检查当天是否已打卡
            EmpAttendanceRecord existingRecord = empAttendanceRecordMapper.getAttendanceByDate(id, attendanceRecord.getAttendanceDate());
            if (existingRecord != null) {
                return "未到签退时间，无法打卡";
            }

            // 保存考勤记录
            empAttendanceRecordMapper.insert(attendanceRecord);
            return "打卡成功";
        }
    }

    /**
     * 获取所有打卡记录
     * @return
     */
    @Override
    public List<EmpAttendanceRecordVo> getListCard() {
        return empAttendanceRecordMapper.getList();
    }

    /**
     * 计算迟到次数
     * @return
     */
    @Override
    public int countLate() {
        // 获取当前日期（北京时间）
        LocalDate localDate = LocalDate.now(ZoneId.of("Asia/Shanghai"));
        Date attendanceDate = Date.from(localDate.atStartOfDay(ZoneId.of("Asia/Shanghai")).toInstant());

        // 构造查询条件：签到时间为 9:00
        LocalTime checkInTime = LocalTime.of(9, 0); // 9:00
        Date checkInDateTime = Date.from(localDate.atTime(checkInTime).atZone(ZoneId.of("Asia/Shanghai")).toInstant());

        // 调用 Mapper 方法查询签到时间为 9:00 的记录数量
        return empAttendanceRecordMapper.countByCheckInTime(attendanceDate, checkInDateTime);
    }

    /**
     * `统计打卡次数`
     * @return
     */
    @Override
    public  List<NameValueResult> count() {
        List<NameValueResult> result = new ArrayList<>();
        NameValueResult nameValueResult = new NameValueResult();
        nameValueResult.setName("已打卡");

        // 获取今天的日期
        LocalDate today = LocalDate.now();

        // 查询今天的打卡人数
        Integer countedIn = empAttendanceRecordMapper.countSignIn(today);
        nameValueResult.setValue(countedIn.toString());
        result.add(nameValueResult);
        // 查询今天的迟到次数未打卡的人数
        NameValueResult valueResult = new NameValueResult();
        valueResult.setName("未打卡");
        Integer countedLate = employeeMapper.count() - countedIn;
        valueResult.setValue(countedLate.toString());
        result.add(valueResult);
        return result;
    }

}
